from flask import request, json
from flask_cors import CORS
from model import User, Userinfo, create_app, db
from is_valid import is_valid
from werkzeug.security import generate_password_hash


app = create_app()
app.app_context().push()
db.create_all()
CORS(app)

@app.route('/register', methods=["POST", "GET"])
def register():
    if request.method == "POST":
        data = request.get_json()
        data = json.loads(data)
        username = data['username']
        passwd = data['password']
        name = data['name']
        studentid = data['studentID']
        gender = data['gender']
        if(not (is_valid(username) and is_valid(name) and is_valid(passwd) and is_valid(studentid))):
            return {
                "status": 0,
                "message": "Illegal parameters"
            }
        exists = User.query.filter_by(username= username).first()
        if(exists is None):
            new_userinfo = Userinfo(name, studentid, gender)
            new_user = User(username, generate_password_hash(passwd), new_userinfo)
            db.session.add(new_userinfo)
            db.session.add(new_user)
            db.session.commit()
            return {
                "status": 1,
                "message": "Register Successful!"
            }             
        else:
            return {
                "status": 0,
                "message": "Username already exists"
            }
    return {
        "status": 0,
        "message": "no get response"
    }
    


if __name__ == '__main__':
    app.run(host='0.0.0.0')